<?php
namespace app\api\model;
/** 
* Document
*/
class Product extends Base {
    protected $hidden =['update_time','delete_time','pivot','from'];
    protected $autoWriteTimestamp = true;

    public function imgs(){
        return $this->hasMany('ProductImage','product_id','id');
    }

    public function property(){
        return $this->hasMany('ProductProperty','product_id','id');
    }



    public function getMainImgUrlAttr($value,$data){
        return Image::getAbsUrl($value,$data['from']);
    }



    /**
     * 获取最近新品
     *
     * @param  $count
     * @return void
     */
    public static function getRecent($count){
        $products = self::limit($count)->order('create_time desc')->select();
        if(empty($products)) return [];
        $collection = collection($products); // 将结果集转化为数据集
        $products = $collection->hidden(['summary'])->toArray();

        return $products;
    }
    
    /**
     * 根据分类获取商品信息
     *
     * @param int $categoryId
     * @return array
     */
    public static function getAllInCategory($categoryId){

        if(empty($categoryId)) return [];
        
        $products = self::where('category_id','=',$categoryId)->select();
        return $products;
    }

    public static function getDetail($id){
        if(empty($id)) return [];
        
        $product = self::get($id,['imgs','imgs.imgUrl','property']);
        if( empty($product)) return [];
        $productArr = $product->toArray();
        $productArr['imgs'] = listSort($productArr['imgs'],'order');
        return $productArr;
    }


}